#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <string>

using namespace std;

const int side_size = 100;
const int nr_of_iterations = 100;
const float life_probability = 0.5f;
bool data[2][side_size][side_size];


bool getBoolean(float true_probability) {
    int f = rand() % 100;
    return f < 100 * true_probability;
}

int getValueOfCell(int k, int i, int j) {
    if(i >= 0 && i < side_size && j >= 0 && j < side_size) {
        if(data[k][i][j]) {
            return 1;
        }
    }
    return 0;
}

int getNumberOfLivingNeighbours(int k, int i, int j) {
    int neighbours = 0;
    for(int t = -1; t <= 1; ++t) {
        for(int v = -1; v <= 1; ++v) {
            neighbours += getValueOfCell(k, i + t, j + v);
        }
    }
    return neighbours - getValueOfCell(k, i, j);
}

void updateCell(int k, int i, int j) {
    int next_k = (k + 1) % 2;
    int neighbours = getNumberOfLivingNeighbours(k, i, j);
    data[next_k][i][j] = data[k][i][j];
    if(neighbours < 2 || neighbours > 3) {
        data[next_k][i][j] = false;
    }
    if(neighbours == 3) {
        data[next_k][i][j] = true;
    }
}

void makeIteration(int k) {
    for(int i = 0; i < side_size; ++i) {
        for(int j = 0; j < side_size; ++j) {
            updateCell(k, i, j);
        }
    }
}

int update() {
    int k = 0;
    for(int i = 0; i < nr_of_iterations; ++i) {
        makeIteration(k);
        k = (k + 1) % 2;
    }
    return k;
}

void fill() {
    for(int i = 0; i < side_size; ++i) {
        for(int j = 0; j < side_size; ++j) {
            data[0][i][j] = getBoolean(life_probability);
        }
    }
}

void data_print(int k, string name) {
    FILE* file = fopen(name.c_str(), "w");
    
    for(int i = 0; i < side_size; ++i) {
        for(int j = 0; j < side_size; ++j) {
            fprintf(file, "%d", getValueOfCell(k, i, j));
        }
        fprintf(file, "\n");
    }   
    fclose(file);
}

int main() {
    srand(time(NULL));
    fill();
    string input("in");
    string output("out");
    data_print(0, input);
    int k = update();
    data_print(k, output);
    
    return 0;
}
